package graphics.primitive;

import java.util.ArrayList;
import java.util.Iterator;

import javax.media.opengl.*;

import mathematics.geometry.Geometry;
import utils.*;

public class Polygon extends BaseDynamicPrimitive 
{
	public Polygon(GL gl, Geometry shape) 
	{
		super(gl, shape);

		this.geometry = shape;
		this.beginMode = GL.GL_POLYGON;	

		this.init(shape);
		
		this.GenerateVertices(gl);
		this.GenerateIndices(gl);
	}
	
	protected void init(Geometry shape)
	{	
		for(Iterator<Point3D> it = shape.iterator(); it.hasNext();)
		{
			Point3D point = it.next();
			if(point.x() < xMin)
			{
				xMin = (float) point.x();
			}
			if(point.x() > xMax)
			{
				xMax = (float) point.x();
			}
			if(point.y() < yMin)
			{
				yMin = (float) point.y();
			}
			if( point.y() > yMax)
			{
				yMax = (float) point.y();
			}
		}
	}

	@Override
	public void GenerateVertices(GL gl) {
		if(this.dynamicVbo.VertexBufferID == 0)
		{
			this.dynamicVbo.GenerateVertexBuffer(gl, this.geometry);
			ArrayList<Point2D> texturesCoords = new ArrayList<Point2D>();
			float xFactor = 1.0f / (this.xMax - this.xMin);
			float yFactor = 1.0f / (this.yMax - this.yMin);
			for(Iterator<Point3D> it = this.geometry.iterator(); it.hasNext();)
			{
				Point3D point = it.next();
				float x = (float) ((point.x() - xMin) * xFactor);
				float y = 1 - (float) ((point.y() - yMin) * yFactor);
				texturesCoords.add(new Point2D(x,y));
			}
			this.dynamicVbo.GenerateTextureBuffer(gl, texturesCoords);
		}
	}

	@Override
	public void GenerateIndices(GL gl) 
	{
		short[] indices = new short[this.dynamicVbo.vertexCount];	
		for(short i = 0; i < this.dynamicVbo.vertexCount; i++ )
		{
			indices[i] = i;
		}
		this.dynamicVbo.GenerateIndexBuffer(gl, indices);
	}
}
